var express = require('express');
var path = require('path');
var formidable = require('formidable');
var fs = require('fs');
var fileBasePath = '/Users/wangzhiyue/Desktop';
var uploadDir = path.join(fileBasePath, '/uploads');
var router = express.Router();

router.get('/upload', function (req, res, next) {
    res.render('upload');
});

router.post('/upload', function (req, res) {
    // create an incoming form object
    var form = new formidable.IncomingForm();

    // specify that we want to allow the user to upload multiple files in a single request
    form.multiples = true;

    // store all uploads in the /uploads directory
    form.uploadDir = uploadDir;

    var filename;

    // every time a file has been uploaded successfully,
    // rename it to it's orignal name
    form.on('file', function (field, file) {
        fs.rename(file.path, path.join(form.uploadDir, file.name));
        filename = file.name;
    });

    // log any errors that occur
    form.on('error', function (err) {
        console.log('An error has occured: \n' + err);
    });

    // once all the files have been uploaded, send a response to the client
    form.on('end', function () {
        res.end(JSON.stringify({code: 'success', url: filename}));
    });

    // parse the incoming request containing the form data
    form.parse(req);
});

router.get('/download', function (req, res) {
    var params = req.query;
    var path = uploadDir + '/' + params.filename;
    fs.readFile(path, function (err, data) {
        if (err) {
            res.end(JSON.stringify({code: 'fail', msg: err}));
        } else {
            res.end(data);
        }
    });
});

module.exports = router;